<!-- 全局背景组件 -->
<template>
  <div class="background-container" :style="backgroundStyle">
    <div class="background-overlay" :style="overlayStyle"></div>
    <div class="background-content">
      <slot></slot>
    </div>
    <div v-if="isImageLoading" class="background-loading">
      <el-icon class="loading-icon"><Loading /></el-icon>
      <span>加载背景图片中...</span>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import axios from '../../utils/axios'

// 背景设置状态
const backgroundType = ref('image')
const backgroundColor = ref('rgba(107, 70, 193, 0.8)')
const gradientType = ref('linear')
const gradientDirection = ref('to bottom right')
const gradientColorStart = ref('rgba(107, 70, 193, 0.8)')
const gradientColorEnd = ref('rgba(72, 41, 178, 0.8)')
const backgroundImage = ref('/backgrounds/ganyu.png')
const opacity = ref(0.9)
const radialShape = ref('circle')
const radialPosition = ref('center')
const isImageLoading = ref(false)
const imageLoadError = ref(false)

// 调试状态
const showDebugInfo = ref(false)
const isBase64Image = computed(() => backgroundImage.value && backgroundImage.value.startsWith('data:image/'))

// 预设主题
const presetThemes = [
  { type: 'gradient', gradientType: 'linear', direction: 'to bottom right', colorStart: 'rgba(107, 70, 193, 0.8)', colorEnd: 'rgba(72, 41, 178, 0.8)' },
  // ... 其他预设主题
]

// 监听背景图片变化
watch(() => backgroundImage.value, (newValue) => {
  if (newValue && backgroundType.value === 'image') {
    preloadImage(newValue)
  }
})

// 预加载图片
const preloadImage = (url) => {
  if (!url) return
  
  // 如果是base64图片，直接设置为已加载状态
  if (url.startsWith('data:image/')) {
    isImageLoading.value = false
    imageLoadError.value = false
    console.log('本地图片已加载 (base64)', url.substring(0, 50) + '...')
    return
  }
  
  isImageLoading.value = true
  imageLoadError.value = false
  console.log('开始加载图片:', url)
  
  const img = new Image()
  img.onload = () => {
    isImageLoading.value = false
    console.log('图片加载成功:', url)
    // 图片加载成功，确保背景类型是图片
    if (backgroundType.value !== 'image') {
      backgroundType.value = 'image'
    }
  }
  img.onerror = (error) => {
    isImageLoading.value = false
    imageLoadError.value = true
    console.error('图片加载失败:', url, error)
    ElMessage.error('背景图片加载失败，请检查URL是否正确')
    // 回退到默认渐变背景
    backgroundType.value = 'gradient'
    // 清空背景图片URL，防止继续尝试加载
    backgroundImage.value = ''
  }
  img.src = url
}

// 计算背景样式
const backgroundStyle = computed(() => {
  if (backgroundType.value === 'solid') {
    return {
      backgroundColor: backgroundColor.value,
    }
  } else if (backgroundType.value === 'gradient') {
    if (gradientType.value === 'linear') {
      return {
        background: `linear-gradient(${gradientDirection.value}, ${gradientColorStart.value}, ${gradientColorEnd.value})`,
      }
    } else {
      return {
        background: `radial-gradient(${radialShape.value} at ${radialPosition.value}, ${gradientColorStart.value}, ${gradientColorEnd.value})`,
      }
    }
  } else if (backgroundType.value === 'image' && backgroundImage.value && !imageLoadError.value) {
    // 检查是否为base64图片或URL
    const isBase64 = backgroundImage.value.startsWith('data:image/')
    
    // 对于base64图片，检查其有效性
    if (isBase64) {
      console.log('使用base64图片作为背景')
    }
    
    return {
      backgroundImage: `url(${backgroundImage.value})`,
      backgroundSize: 'cover',
      backgroundPosition: 'center',
      backgroundRepeat: 'no-repeat',
      backgroundAttachment: 'fixed',
      transition: isBase64 ? 'none' : 'background-image 0.5s ease', // base64图片不使用过渡效果，避免内存问题
    }
  }
  
  // 默认返回渐变背景
  return {
    background: `linear-gradient(to bottom right, rgba(107, 70, 193, 0.8), rgba(72, 41, 178, 0.8))`,
  }
})

// 计算叠加层样式
const overlayStyle = computed(() => {
  return {
    opacity: 1 - opacity.value,
    backgroundColor: '#000',
  }
})

// 应用预设主题
const applyPresetTheme = (theme) => {
  backgroundType.value = theme.type
  
  if (theme.type === 'solid') {
    backgroundColor.value = theme.color
  } else if (theme.type === 'gradient') {
    gradientType.value = theme.gradientType
    if (theme.gradientType === 'linear') {
      gradientDirection.value = theme.direction
    }
    gradientColorStart.value = theme.colorStart
    gradientColorEnd.value = theme.colorEnd
  }
}

// 监听背景设置更新事件
const handleBackgroundSettingsUpdated = () => {
  console.log('接收到背景设置更新事件')
  // 延迟一点加载设置，确保localStorage已更新
  setTimeout(() => {
    loadSettings()
  }, 100)
}

// 重新加载设置
const reloadSettings = () => {
  console.log('手动重新加载设置')
  loadSettings()
}

// 测试本地存储
const testLocalStorage = () => {
  try {
    // 测试写入
    localStorage.setItem('test_key', 'test_value')
    console.log('localStorage写入测试成功')
    
    // 测试读取
    const testValue = localStorage.getItem('test_key')
    console.log('localStorage读取测试:', testValue)
    
    // 测试删除
    localStorage.removeItem('test_key')
    console.log('localStorage删除测试成功')
    
    // 测试背景设置
    const savedSettings = localStorage.getItem('background_settings')
    console.log('当前背景设置:', savedSettings ? JSON.parse(savedSettings) : '无')
    
    // 显示成功消息
    const successMsg = document.createElement('div')
    successMsg.textContent = '本地存储测试成功'
    successMsg.style.position = 'fixed'
    successMsg.style.bottom = '20px'
    successMsg.style.left = '50%'
    successMsg.style.transform = 'translateX(-50%)'
    successMsg.style.background = 'rgba(21, 178, 129, 0.9)'
    successMsg.style.color = 'white'
    successMsg.style.padding = '10px 20px'
    successMsg.style.borderRadius = '4px'
    successMsg.style.zIndex = '9999'
    document.body.appendChild(successMsg)
    
    // 3秒后移除消息
    setTimeout(() => {
      document.body.removeChild(successMsg)
    }, 3000)
  } catch (error) {
    console.error('本地存储测试失败:', error)
    
    // 显示错误消息
    const errorMsg = document.createElement('div')
    errorMsg.textContent = '本地存储测试失败: ' + error.message
    errorMsg.style.position = 'fixed'
    errorMsg.style.bottom = '20px'
    errorMsg.style.left = '50%'
    errorMsg.style.transform = 'translateX(-50%)'
    errorMsg.style.background = 'rgba(220, 38, 38, 0.9)'
    errorMsg.style.color = 'white'
    errorMsg.style.padding = '10px 20px'
    errorMsg.style.borderRadius = '4px'
    errorMsg.style.zIndex = '9999'
    document.body.appendChild(errorMsg)
    
    // 3秒后移除消息
    setTimeout(() => {
      document.body.removeChild(errorMsg)
    }, 3000)
  }
}

// 从localStorage加载背景设置
const loadSettings = () => {
  try {
    const savedSettings = localStorage.getItem('background_settings')
    if (savedSettings) {
      const settings = JSON.parse(savedSettings)
      
      // 更新背景类型
      if (settings.backgroundType) {
        backgroundType.value = settings.backgroundType
      }
      
      // 更新不同类型背景的设置
      if (settings.backgroundColor) {
        backgroundColor.value = settings.backgroundColor
      }
      
      if (settings.gradientType) {
        gradientType.value = settings.gradientType
      }
      
      if (settings.gradientDirection) {
        gradientDirection.value = settings.gradientDirection
      }
      
      if (settings.gradientColorStart) {
        gradientColorStart.value = settings.gradientColorStart
      }
      
      if (settings.gradientColorEnd) {
        gradientColorEnd.value = settings.gradientColorEnd
      }
      
      if (settings.backgroundImage) {
        backgroundImage.value = settings.backgroundImage
      }
      
      if (settings.opacity !== undefined) {
        opacity.value = settings.opacity
      }
      
      if (settings.radialShape) {
        radialShape.value = settings.radialShape
      }
      
      if (settings.radialPosition) {
        radialPosition.value = settings.radialPosition
      }
      
      console.log('背景设置已从localStorage加载')
    } else {
      console.log('未找到保存的背景设置，使用默认设置')
    }
  } catch (error) {
    console.error('加载背景设置失败:', error)
  }
}

onMounted(() => {
  console.log('Background组件已挂载')
  loadSettings()
  // 添加自定义事件监听器
  window.addEventListener('background-settings-updated', handleBackgroundSettingsUpdated)
})

onUnmounted(() => {
  console.log('Background组件已卸载')
  // 移除自定义事件监听器
  window.removeEventListener('background-settings-updated', handleBackgroundSettingsUpdated)
})
</script>

<style scoped>
.background-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -2;
  transition: background 0.5s ease;
  pointer-events: none; /* 允许鼠标事件穿透背景 */
}

.background-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  z-index: -1;
  transition: opacity 0.5s ease;
  pointer-events: none; /* 允许鼠标事件穿透叠加层 */
}

.background-content {
  position: relative;
  z-index: 1;
  min-height: 100vh;
  pointer-events: auto; /* 确保内容区域可以接收鼠标事件 */
}

.background-loading {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 15px 20px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 10px;
  z-index: 1000;
  pointer-events: none;
}

.loading-icon {
  font-size: 20px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style> 